//package com.neudu.glsb.controller;
//import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
//import com.github.pagehelper.PageHelper;
//import com.github.pagehelper.PageInfo;
//import com.neudu.glsb.commons.JSONReturn;
//import com.neudu.glsb.pojo.Ingredients;
//import com.neudu.glsb.service.IngredientsService;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.util.ObjectUtils;
//import org.springframework.web.bind.annotation.*;
//import java.util.List;
//import java.util.Map;
//
//@RestController
//public class IngredientsController {
//
//    @Autowired
//    private IngredientsService ingredientsService;
//    @Autowired
//    private JSONReturn jsonReturn;
//
//    @PostMapping("get_all_ingredients")
//    public String getAll(@RequestBody Map<String, Object> pageInfoMap) {
//        try {
//            Integer pageNum = (Integer) pageInfoMap.get("pageNum");
//            Integer pageSize = (Integer) pageInfoMap.get("pageSize");
//            PageHelper.startPage(pageNum, pageSize);
//            List<Ingredients> list = ingredientsService.list();
//            PageInfo<Ingredients> pageInfoReturn = new PageInfo<>(list);
//            return jsonReturn.returnSuccess(pageInfoReturn);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return jsonReturn.returnError(e.getMessage());
//        }
//    }
//
//    @PostMapping("get_ingredient_by")
//    public String getByCondition(@RequestBody Map<String, Object> conditionMap) {
//        try {
//            Integer pageNum = (Integer) conditionMap.get("pageNum");
//            Integer pageSize = (Integer) conditionMap.get("pageSize");
//            String ingredientName = (String) conditionMap.get("ingredientName");
//
//            PageHelper.startPage(pageNum, pageSize);
//            LambdaQueryWrapper<Ingredients> queryWrapper = new LambdaQueryWrapper<>();
//            if (!ObjectUtils.isEmpty(ingredientName)) {
//                queryWrapper.like(Ingredients::getIngredientName, ingredientName);
//            }
//
//            List<Ingredients> ingredients = ingredientsService.list(queryWrapper);
//            PageInfo<Ingredients> pageInfo = new PageInfo<>(ingredients);
//            return jsonReturn.returnSuccess(pageInfo);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return jsonReturn.returnError(e.getMessage());
//        }
//    }
//
//    @PostMapping("add_one_ingredient")
//    public String addOne(@RequestBody Ingredients ingredient) {
//        try {
//            ingredientsService.save(ingredient);
//            return jsonReturn.returnSuccess();
//        } catch (Exception e) {
//            e.printStackTrace();
//            return jsonReturn.returnError(e.getMessage());
//        }
//    }
//
//    @PostMapping("getingredientby_id")
//    public String getById(@RequestBody Map<String, Integer> idMap) {
//        try {
//            Integer id = idMap.get("id");
//            if (ObjectUtils.isEmpty(id)) {
//                return jsonReturn.returnError("ID不能为空");
//            }
//            Ingredients ingredient = ingredientsService.getById(id);
//            return jsonReturn.returnSuccess(ingredient);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return jsonReturn.returnError(e.getMessage());
//        }
//    }
//
//    @PostMapping("modifyingredientby_id")
//    public String modifyById(@RequestBody Ingredients ingredient) {
//        try {
//            if (ObjectUtils.isEmpty(ingredient.getId())) {
//                return jsonReturn.returnError("更新失败，id 不能为空");
//            }
//            boolean success = ingredientsService.updateById(ingredient);
//            if (success) {
//                return jsonReturn.returnSuccess();
//            } else {
//                return jsonReturn.returnError("更新失败，未找到对应的材料信息");
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            return jsonReturn.returnError(e.getMessage());
//        }
//    }
//
//    @PostMapping("removeingredient_by_id")
//    public String removeById(@RequestBody Map<String, Integer> idMap) {
//        try {
//            Integer id = idMap.get("id");
//            if (ObjectUtils.isEmpty(id)) {
//                return jsonReturn.returnError("ID不能为空");
//            }
//            boolean success = ingredientsService.removeById(id);
//            if (success) {
//                return jsonReturn.returnSuccess();
//            } else {
//                return jsonReturn.returnError("删除失败，未找到对应的材料信息");
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            return jsonReturn.returnError(e.getMessage());
//        }
//    }
//}
package com.neudu.glsb.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.neudu.glsb.commons.JSONReturn;
import com.neudu.glsb.dto.IngredientsPageDTO;
import com.neudu.glsb.pojo.Ingredients;
import com.neudu.glsb.service.IngredientsService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/ingredients")
public class IngredientsController {

    @Autowired
    private IngredientsService ingredientsService;
    @Autowired
    private JSONReturn jsonReturn;


    /* ============================ 单条查询 ============================ */
    @GetMapping("/{id}")
    public String getById(@PathVariable Integer id) {
        try {
            Ingredients ing = ingredientsService.getById(id);
            if (ing == null) {
                return jsonReturn.returnError("记录不存在");
            }
            return jsonReturn.returnSuccess(ing);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    /* ============================ 新增 / 修改 ============================ */
    @PostMapping
    public String saveOrUpdate(@RequestBody Ingredients ing) {
        try {
            boolean flag = ingredientsService.saveOrUpdate(ing);
            return flag ? jsonReturn.returnSuccess()
                    : jsonReturn.returnError("操作失败");
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    /* ============================ 删除 ============================ */
    @DeleteMapping("/{id}")
    public String remove(@PathVariable Integer id) {
        try {
            boolean flag = ingredientsService.removeById(id);
            return flag ? jsonReturn.returnSuccess()
                    : jsonReturn.returnError("删除失败，记录不存在");
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    /* ============================ 入库：stock/quantity 同时增加 ============================ */
    @PostMapping("/stock/in")
    public String stockIn(@RequestBody Map<String, Object> param) {
        try {
            Integer id = (Integer) param.get("id");
            BigDecimal amount = new BigDecimal(param.get("amount").toString());
            Ingredients ing = ingredientsService.getById(id);
            if (ing == null) {
                return jsonReturn.returnError("记录不存在");
            }
            ing.setStock(ing.getStock() + amount.intValue());
            ing.setQuantity(ing.getQuantity() + amount.intValue());
            ingredientsService.updateById(ing);
            return jsonReturn.returnSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    /* ============================ 旧接口兼容（可选保留） ============================ */
    /**
     * 模拟员工接口的 PageHelper 分页写法
     * 十行一换页，返回 PageInfo 格式
     */
//    @PostMapping("/get_all_ingredients")
//    public String getAll(@RequestBody Map<String, Object> pageInfoMap) {
//        try {
//            Integer pageNum = (Integer) pageInfoMap.get("pageNum");
//            Integer pageSize = 10;                       // 十行一换页
//            PageHelper.startPage(pageNum, pageSize);
//            List<Ingredients> list = ingredientsService.list();
//            PageInfo<Ingredients> pageInfo = new PageInfo<>(list);
//
//            // 只抽出前端需要的两个字段
//            Map<String, Object> rsp = new HashMap<>();
//            rsp.put("records", pageInfo.getList());      // 当前页数据
//            rsp.put("total", pageInfo.getTotal());       // 总条数
//
//            return jsonReturn.returnSuccess(rsp);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return jsonReturn.returnError(e.getMessage());
//        }
//    }
    /**
     * 分页 + 多条件（名称模糊、类型、库存状态）
     * 纯 PageHelper + Lambda 写法
     */
    @PostMapping("/get_all_redients")   // 前面不要再加 /glab
    public String getAll(@RequestBody Map<String, Object> pageInfoMap) {
        try {
            Integer pageNum = (Integer) pageInfoMap.getOrDefault("pageNum", 1);
            Integer pageSize = 10;                       // 固定 10 行
            PageHelper.startPage(pageNum, pageSize);

            List<Ingredients> list = ingredientsService.list();
            PageInfo<Ingredients> pageInfo = new PageInfo<>(list);

            Map<String, Object> rsp = new HashMap<>();
            rsp.put("records", pageInfo.getList());
            rsp.put("total", pageInfo.getTotal());

            return jsonReturn.returnSuccess(rsp);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }
    /**
     * 分页 + 多条件（名称/供应商模糊、类型、库存状态）
     * 十行一换页，返回统一格式
     */
    @PostMapping("/search")
    public String searchIngredients(@RequestBody Map<String, Object> param) {
        try {
            int pageNum  = (Integer) param.getOrDefault("pageNum", 1);
            int pageSize = 10;
            String keyword   = (String) param.get("keyword");      // 名称/供应商模糊
            String type      = (String) param.get("ingredientType");
            String stockStat = (String) param.get("stockStatus");

            PageHelper.startPage(pageNum, pageSize);

            LambdaQueryWrapper<Ingredients> w = new LambdaQueryWrapper<>();
            w.like(StringUtils.hasText(keyword), Ingredients::getIngredientName, keyword)
                    .or()
                    .like(StringUtils.hasText(keyword), Ingredients::getSupplier, keyword);
            w.eq(StringUtils.hasText(type), Ingredients::getIngredientType, type);
            if ("normal".equals(stockStat)) {
                w.apply("stock >= threshold");
            } else if ("warning".equals(stockStat)) {
                w.apply("stock < threshold");
            }

            List<Ingredients> list = ingredientsService.list(w);
            PageInfo<Ingredients> page = new PageInfo<>(list);

            Map<String, Object> rsp = new HashMap<>();
            rsp.put("records", page.getList());
            rsp.put("total", page.getTotal());
            return jsonReturn.returnSuccess(rsp);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

}